<?php
class Attachment extends CComponent {
	private $_baseUrl;
	private $_basePath;
	private $_bucket;
	private $_dataUrl;

	public function __construct () {}

	public function init () {}

	public function setBaseUrl ($url = null) {
		$this->_baseUrl = $url ? $url : Yii::app()->getBaseUrl() . '/data/attachment';
		return $this;
	}

	public function getBaseUrl () {
		if ($this->_baseUrl == null)
			$this->setBaseUrl();
		return $this->_baseUrl;
	}

	public function setBasePath ($path = null) {
		$this->_basePath = $path ? $path : Yii::getPathOfAlias('webroot.data.attachment');
		return $this;
	}

	public function getBasePath () {
		if ($this->_basePath == null)
			$this->setBasePath();
		return $this->_basePath;
	}

	/**
	 * 创建attachment文件名
	 * 
	 * @param string $filename        	
	 * @param string $module        	
	 * @param boolean $mark
	 *        	是否标记文件
	 */
	public function getFileName ($filename, $module = 'temp', $mark = false) {
		list($name, $ext) = explode('.', $filename);
		return $module . date('/y/m/d/') . md5(YII_BEGIN_TIME . rand() . $name) . '.' . $ext;
	}

	/**
	 * 获取完整路径
	 * 
	 * @param string $file
	 *        	附件目录相对路径的文件名(首字不能带/) 如 temp/xxx.jpg
	 */
	public function getPath ($file) {
		return $this->getBasePath() . '/' . $file;
	}

	/**
	 * 获取附件url地址
	 * 
	 * @param string $file
	 *        	附件目录相对路径的文件名(首字不能带/) 如 temp/xxx.jpg
	 */
	public function getUrl ($file) {
		return $this->getBaseUrl() . '/' . $file;
	}

	/**
	 * 获取附件缩略图地址
	 * 
	 * @param string $target        	
	 * @param string $maxWidth        	
	 * @param string $maxHeight        	
	 * @param boolean $absoluteUrl
	 *        	是否绝对地址
	 * @param boolean $create
	 *        	如果文件不存在是否创建
	 */
	public function getThumb ($target, $maxWidth = 190, $maxHeight = 130, $absoluteUrl = false, $create = true) {
		$targetInfo = pathinfo($target);
		$targetThumbDir = 'thumb/' . substr($targetInfo['filename'], 0, 2);
		$targetThumb = $targetThumbDir . '/' . $maxWidth . 'X' . $maxHeight . '_' . $targetInfo['basename'];
		if ($create && !is_file($targetThumbPath = $this->getPath($targetThumb)) && FileHelper::mkdir(dirname($targetThumbPath))) {
			Image::create($this->getPath($target))->resize($maxWidth, $maxHeight)->save($targetThumbPath);
		}
		return $absoluteUrl ? $this->getUrl($targetThumb) : $targetThumb;
	}
}
?>